﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using FlanProjectData.Managers;
using FlanProjectData.Helpers;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Input;
using FlanProjectData.GameObjects;
using FlanProject.ScreenMenu;

namespace FlanProject.ScreenMenu
{
    public class NewGameScreen : InterfaceScreen
    {
        private static Logger logger = new Logger("NewGameScreen");

        private PopupComponent popupInformation;

        #region attributs
        private String NameTexte = "My name...";

        private String dossier = @"Saves\"; // chemin où se trouve les dossiers de sauvegarde

        private float widthDistanceButton = (float)0.30;    //Define the width position in % of the button ("retour")
        private float heightDistanceButton = (float)0.60;   //Define the height position in % of the button ("retour")

        private float widthPercentButton = (float)0.43;		//Define the width in % of the button
        private float heightPercentButton = (float)0.09;	//Define the height in % of the button

        private float widthDistanceTextUp = (float)0.04;   //Define the width position in % of the title ("New Game")
        private float heightDistanceTextUp = (float)0.14;   //Define the height position in % of the title ("New game")

        private float widthPercentText = (float)0.30;//Define the width position in % of the text ("enter your name:")
        private float heighthPercentText = (float)0.30; //Define the height position in % of the text ("enter your name:")

        private float widthPercentTextName = (float)0.35; //Define the width position in % of the text ("My name")
        private float heightPercentTextName = (float)0.40; //Define the height position in % of the title ("My name")

        private float distanceBetween2Button = (float)0.12;	//Define the distance in % of 2 button

        private float policeSize = 1;

        #endregion

        #region constructeur
        public NewGameScreen()
        {
            int i = 0;

            this.lstMenuEntrySelectable.Add(new MenuEntry(NameTexte,
               new Vector2((float)windowsWidth * widthPercentTextName,
                   (float)windowsHeight * heightPercentTextName),
                   true, Color.Black, policeSize));

            #region add Button

            this.lstMenuEntrySelectable.Add(new MenuEntry("Begin",
                new Vector2((float)windowsWidth * widthDistanceButton,
                        (float)windowsHeight * heightDistanceButton + ((float)windowsHeight * (distanceBetween2Button * i++))),
                new Vector2((float)windowsWidth * widthPercentButton,
                    (float)windowsHeight * heightPercentButton), policeSize));
            //The party BEGIN!!!

            this.lstMenuEntrySelectable.Add(new MenuEntry("Retour",
               new Vector2((float)windowsWidth * widthDistanceButton,
                       (float)windowsHeight * heightDistanceButton + ((float)windowsHeight * (distanceBetween2Button * i++))),
               new Vector2((float)windowsWidth * widthPercentButton,
                   (float)windowsHeight * heightPercentButton), policeSize));
            this.lstMenuEntrySelectable[2].Selected += this.ExitScreen;

            #endregion

            #region add text
            this.lstMenuEntryUnselectable.Add(new MenuEntry("New Game",
                new Vector2((float)windowsWidth * widthDistanceTextUp,
                    (float)windowsHeight * heightDistanceTextUp),
                    true, Color.Black, policeSize));

            this.lstMenuEntryUnselectable.Add(new MenuEntry("Enter your name: ",
                new Vector2((float)windowsWidth * (float)widthPercentText,
                    (float)windowsHeight * (float)heighthPercentText),
                    true, Color.Black, policeSize));

            #endregion
        }
        #endregion

        #region LoadContent
        public override void LoadContent(ContentManager content)
        {
            this.background = content.Load<Texture2D>(@"Sprites\Menus\commonBackgroundMenu");

            // calculate the scale of the background
            base.calcScaleBackground(windowsHeight, windowsWidth);

            // Use virtual definition
            base.LoadContent(content);

        }
        #endregion

        public override void Draw(SpriteBatch sb)
        {
            base.Draw(sb);
            if (this.popupInformation != null)
            {
                this.popupInformation.Draw(sb);
            }
        }

        public override void Update()
        {
            if (this.popupInformation == null || this.popupInformation.IsExiting)
            {
                this.IsFocused = true;
                this.popupInformation = null;
            }
            base.Update();
        }


        #region Overrided HandleInput
        public override void HandleInput()
        {
            if (this.popupInformation == null)
            {
                if (InputManager.IsActionTriggered(InputManager.Action.Up))
                {
                    selectedIndex = (selectedIndex - 1 + lstMenuEntrySelectable.Count) % lstMenuEntrySelectable.Count;
                    logger.Debug(selectedIndex.ToString());
                }
                else if (InputManager.IsActionTriggered(InputManager.Action.Down))
                {
                    selectedIndex = Math.Abs(selectedIndex + 1) % lstMenuEntrySelectable.Count;
                    logger.Debug(selectedIndex.ToString());
                }
                // Validation of selected index
                else if (InputManager.IsActionTriggered(InputManager.Action.Ok))
                {
                    logger.Info("Validation on :" + selectedIndex.ToString());

                    if (selectedIndex == 1) // if the bouton "begin" is selected
                    {
                        if (createSave())
                        {
                            this.filesName = this.lstMenuEntrySelectable[0].message;
                            // this.IsLoadingGame = true;
							this.imChild = new IntroductionScreen(this.filesName);
							this.imChild.LoadContent(this.Content);
							this.imChild.Visible = true;
							this.Visible = false;
                            logger.Debug("demande de creation de la partie");
                        }

                    }

                    // if the name is selected, the focus change.
                    if (selectedIndex == 0)
                    {
                        selectedIndex = Math.Abs(selectedIndex + 1) % lstMenuEntrySelectable.Count;
                        logger.Debug(selectedIndex.ToString());
                    }

                    // Execute MenuEntryAction
                    this.lstMenuEntrySelectable[selectedIndex].OnSelectEntry();

                }
                else if (InputManager.IsActionTriggered(InputManager.Action.Exit))
                {
                    logger.Warn("Fermeture du programme");
                    this.ExitScreen();
                }
                else if (InputManager.IsActionTriggered(InputManager.Action.Return))
                {
                    // if the name is selected
                    if (selectedIndex == 0)
                    {
                        this.DelName();
                    }
                }
                else
                {
                    // if the name is selected
                    if (selectedIndex == 0)
                    {
                        this.addLetter(InputManager.getKeyPressed());
                    }

                }
            }
            else
            {
                this.popupInformation.HandleInput();
            }

        }

        #endregion



        #region methodes
        /// <summary>
        /// delate one letter at time for the character's name
        /// </summary>
        public void DelName()
        {
            String texte = this.lstMenuEntrySelectable[0].message;
            String resultat = "";
            int size = texte.Length;
            int i = 0;
            while (i < size - 1)
            {
                resultat = resultat + texte[i];
                i++;
            }
            this.lstMenuEntrySelectable[0].message = resultat;

        }
        /// <summary>
        /// add one letter to the character's name
        /// </summary>
        public void addLetter(String letter)
        {
            this.lstMenuEntrySelectable[0].message += letter;
        }
        /// <summary>
        /// Creation of the save files
        /// </summary>
        public Boolean createSave()
        {
            Boolean success = true;
            Boolean retour = false;

            if (!Directory.Exists(@"Content\Saves"))
            {
                Directory.CreateDirectory(@"Content\Saves");
            }

            DirectoryInfo dir = new DirectoryInfo(@"Content\" + dossier);
            DirectoryInfo[] listeDossier = dir.GetDirectories();

            logger.Debug("nom du repertoire: " + dir.FullName);
            logger.Debug("nbr repertoire: " + listeDossier.Length);

            logger.Debug("sav quon veu crée:" + this.lstMenuEntrySelectable[0].message);

            for (int y = 0; y < listeDossier.Length; y++)
            {
                if (this.lstMenuEntrySelectable[0].message.Equals(listeDossier.ElementAt<DirectoryInfo>(y).Name)) // il existe deja  une sauvegarde du meme nom
                {
                    logger.Debug("il existe deja un fichier de sauvegarde du mm nom");
                    success = false;
                    // On affiche une popup.
                    string message = "";
                    message += "There already is a saving under that name, ";
                    message += "Please change it.";

                    this.IsFocused = false;
                    this.popupInformation = new PopupComponent(message, 3,
                        new Vector2(100, 100));
                    this.popupInformation.LoadContent(this.Content);
                    this.popupInformation.Visible = true;

                }
                logger.Debug(listeDossier.ElementAt<DirectoryInfo>(y).Name);
            }
            if (success == true)
            {
                if (listeDossier.Length >= 3) // trop de sauvegarde
                {
                    // chargement de la fenetre qui va faire effacé une sauvegarde

                    logger.Info("Loading New Game Screen");

                    this.imChild = new DelSaveScreen();
                    this.imChild.LoadContent(this.Content);
                    this.Visible = false;
                    this.imChild.Visible = true;


                }
                else
                {
                    Party maParty = new Party(); // on crée une partie de base
                    maParty.Position = new Vector2(32, 32); // on defini la position de base
                    maParty.inventory = new Inventory();
                    dir.CreateSubdirectory(this.lstMenuEntrySelectable[0].message); // on crée le repertoire
                    maParty.creationSauvegarde(Content, "Data/Party/Character"); // on la seriablise
                    maParty.PlayerList[0].Name = this.lstMenuEntrySelectable[0].message;//on definie le nom du 1er perso
                    maParty.save(this.lstMenuEntrySelectable[0].message);// on la sauvegarde dans le bon fichier
                    retour = true;

                    // on crée le fichier et la sauvegarde
                    /*
                    ; // juste le fichier
                    // on copy/colle le fichier de sauvegarde dedans.
                    logger.Debug(dir.FullName);
                    File.Copy(@"Content/Data/Characters/Character.xnb", dir.FullName + @"/" + this.lstMenuEntrySelectable[0].message + @"/save.xnb",true);
                    retour = true;
                     * */
                }
            }

            return retour;
        }


        #endregion

    }
}
